﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Navigation;
using System.Windows.Threading;
using log4net;
using Lhn.Ds.Core.Exceptions;

namespace Lhn.Ds.Core
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        public static readonly ILog Log =
            LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public App()
        {
            TaskScheduler.UnobservedTaskException += Task_DispatcherUnhandledException;
            Dispatcher.UnhandledException += App_DispatcherUnhandledException;
            
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Application.Current.DispatcherUnhandledException += App_DispatcherUnhandledException;
        }

        public CompositionContainer Container { get; set; }

        protected override void OnLoadCompleted(NavigationEventArgs e)
        {
            base.OnLoadCompleted(e);
           // DispatcherUnhandledException += App_DispatcherUnhandledException;
            //log4net.Config.XmlConfigurator.Configure();
           

        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            //Log
            ProccessException(sender,e, e.ExceptionObject as Exception);
        }

        private void Task_DispatcherUnhandledException(object sender, UnobservedTaskExceptionEventArgs e)
        {

            if (ProccessException(sender, e, e.Exception))
            {
                e.SetObserved();
            }
            e.SetObserved();
            
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            DsContext.InstanceData.InitContainer();
        }

        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            if (ProccessException(sender, e, e.Exception))
            {
                e.Handled = true;
            }

            e.Handled = true;
        }

        private bool ProccessException(object sender,EventArgs args,System.Exception e)
        {
            return DsContext.InstanceData.ProccessException(e);
        }
    }
}